package com.back.security;

import com.back.common.enums.DeleteFlag;
import com.back.common.enums.RoleCode;
import com.back.entity.User;
import com.back.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;

/**
 * 自定义UserDetailsService实现
 * 用于Spring Security从数据库中加载用户信息和权限
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    
    @Autowired
    private IUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        queryWrapper.eq("deleted", DeleteFlag.NOT_DELETED.getValue());
        
        User user = userService.getOne(queryWrapper);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        
        // 获取用户角色
        Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
        if (user.getRole().equals(RoleCode.ADMIN.getCode())) {
            authorities.add(new SimpleGrantedAuthority("admin"));
        } else if (user.getRole().equals(RoleCode.EMPLOYER.getCode())) {
            authorities.add(new SimpleGrantedAuthority("company"));
        } else if (user.getRole().equals(RoleCode.JOB_SEEKER.getCode())) {
            authorities.add(new SimpleGrantedAuthority("job_seeker"));
        }
        
        // 返回UserDetails实现
        return new org.springframework.security.core.userdetails.User(
            user.getUsername(),
            user.getPassword(),
            authorities
        );
    }
} 